<?php
namespace App\Tools;

class File
{
    /*
     * 读取文件      
     */
    public static function getFileLines($filename, $startLine = 1, $endLine = 50, $method = 'rb')
    {
        $content = array();
        $count = $endLine - $startLine;
        if($count <= 0)
        {
            return $content;
        }

        //判断php版本（因为要用到SplFileObject，PHP>=5.1.0）
        if(version_compare(PHP_VERSION, "5.1.0", ">="))
        {
            $fp = new \SplFileObject($filename);
            //转到第N行, seek方法参数从0开始计数
            $fp->seek($startLine - 1);
            for ($i = 0; $i <= $count; ++$i)
            {
                //current()获取当前行内容
                $content[] = $fp->current();
                // 下一行
                $fp->next();
            }
        }
        else
        {
            $fp = fopen($filename, $method);
            if(!$fp) return 'error:can not read file';
            //跳过前$startLine行
            for ($i=1;$i < $startLine;++$i) {
                fgets($fp);
            }
            //读取文件行内容
            for($i;$i <= $endLine;++$i){
                $content[]=fgets($fp);
            }
            fclose($fp);
        }
        //array_filter过滤：false,null,''
        return array_filter($content);
    }
    
    /*写入文件*/
    public static function wirteFile($filePath = '',$content = '')
    {
        if(empty($filePath) || empty($content))
        {
            return '';
        }
        $br     = "\n";
        $dir    = dirname($filePath);
        if(!is_dir($dir))
        {
            mkdir($dir,0777,true);
        }
        //$content    = iconv("UTF-8","GBK//IGNORE",$content);
        $content    = mb_convert_encoding($content, "GBK", "UTF-8");
        $content    = trim($content,$br);
        $content = $content.$br;
        return file_put_contents($filePath,$content,FILE_APPEND|LOCK_EX);
    }
    
    public static function wirteContents($contents = array())
    {
        foreach ($contents as $filePath => $content)
        {
             self::wirteFile($filePath, $content);
        }
    }
}